package net.fdukedom.o3i.icq;

import net.fdukedom.o3i.util.NumberUtil;
import java.io.IOException;
import java.io.InputStream;

/**
 * This is utility class to Read FLAP entries from the stream. 
 * 
 * @author duke
 */
public class FlapReader {

    /**
     * Stream to read FLAPs from.
     */
    private final InputStream stream;

    public FlapReader(InputStream stream) {
        this.stream = stream;
    }

    public InputStream getStream() {
        return stream;
    }
    
    /**
     * Reads FLAP entity from stream.
     * 
     * @return FLAP
     * 
     * @throws java.io.IOException if an error occured
     */
    public Flap read() throws IOException {
        byte[] flapHeaders = new byte[Flap.HEADERS_SIZE];
        stream.read(flapHeaders);
        byte channelId = flapHeaders[FlapByteOrder.CHANNEL_ID_BYTE.getPosition()]; 
        short sequenceNumber = NumberUtil.convertToShort(flapHeaders[FlapByteOrder.SEQUENCE_NUMBER_START_BYTE.getPosition()],
                flapHeaders[FlapByteOrder.SEQUENCE_NUMBER_START_BYTE.getPosition() + 1]);
        short dataSize = NumberUtil.convertToShort(flapHeaders[FlapByteOrder.DATA_LENGTH_START_BYTE.getPosition()],
                flapHeaders[FlapByteOrder.DATA_LENGTH_START_BYTE.getPosition() + 1]);
        byte[] data = new byte[dataSize];
        stream.read(data);
        return new Flap(channelId, (short) sequenceNumber, data);
    }

    /**
     * Closes input stream.
     * 
     * @throws java.io.IOException if an error occured.
     */
    public void close() throws IOException {
        stream.close();
    }

}
